<template>

<!-- 先判断 roleName 是否有值，无值时显示加载中 -->
<div v-if="!roleName">
  <el-loading v-loading="true" element-loading-text="加载中...">
    <div style="height: 1000px;"></div> <!-- 占位高度，避免布局抖动 -->
  </el-loading>
</div>

<div class="other" v-if="roleName === '护理员'">
    <div class="result">
      <h2>审批结果</h2>
    </div>
    <div class="ca">
      <img src="/src/assets/images/注意1.png">
      <div>
        <h3>审批中</h3>
      </div>
      <div class="oth">稍等，退住申请单正在审批中，若该申请单长时间未处理，请联系(审批角色)！</div>
      <!-- 操作记录区域 -->
      <el-card class="operation-record-card">
        <div class="record-header">
          <h3>操作记录</h3>
          <div class="record-status">
            <span class="status-badge processing">审批中</span>
          </div>
        </div>
        <div class="record-timeline" v-if="operationRecords.length">
          <div 
            v-for="(record, index) in operationRecords" 
            :key="index"
            class="timeline-item"
            :class="{ 
              'completed': record.status === '已发起' || record.status === '已通过',
              'processing': record.status === '审批中' || record.status === '已拒绝'
            }"
          >
            <div class="timeline-dot">
              <el-icon 
                :color="record.status === '已拒绝' ? '#f56c6c' : (record.status === '已通过' || record.status === '已发起' ? '#67c23a' : '#409eff')" 
                size="16"
              >
                <Check v-if="record.status === '已通过' || record.status === '已发起'" />
                <Close v-else-if="record.status === '已拒绝'" />
                <Clock v-else />
              </el-icon>
            </div>
            <div class="timeline-content">
              <div class="timeline-title">{{ record.action }}</div>
              <div class="timeline-desc">{{ record.operator }} ({{ record.status }})</div>
              <div class="timeline-time">{{ record.time || '-' }}</div>
              <div class="timeline-opinion" v-if="record.opinion && record.opinion !== '-'">
                <div class="opinion-label">审批意见：</div>
                <div class="opinion-content">{{ record.opinion }}</div>
              </div>
            </div>
          </div>
        </div>
        <div v-else class="loading-tip">加载中...</div>
      </el-card>
    </div>
  </div>

  <div class="third-page" v-else>
    <div class="content-wrapper">
      <div class="left-content">
        <!-- 基本信息区域 -->
        <el-card class="basic-info-card">
          <h3>基本信息</h3>
          <ul class="info-list">
            <li><span class="label">老人姓名</span><span class="value">{{ form.elderName || '-' }}</span></li>
            <li><span class="label">老人身份证号</span><span class="value">{{ form.idCard || '-' }}</span></li>
            <li><span class="label">联系方式</span><span class="value">{{ form.phone || '-' }}</span></li>
            <li><span class="label">费用期限</span><span class="value">{{ form.feePeriod || '-' }}</span></li>
            <li><span class="label">护理等级</span><span class="value">{{ form.nursingLevel || '-' }}</span></li>
            <li><span class="label">入住床位</span><span class="value">{{ form.bed || '-' }}床位</span></li>
            <li><span class="label">签约合同</span><span class="value">{{ form.contract || '-' }} <a href="#" class="view-link">查看</a></span></li>
            <li><span class="label">养老顾问</span><span class="value">{{ form.advisor || '-' }}</span></li>
            <li><span class="label">护理员</span><span class="value">{{ form.nurse || '-' }}</span></li>
          </ul>
        </el-card>

        <!-- 申请信息区域 -->
        <el-card class="apply-info-card">
          <h3>申请信息</h3>
          <ul class="info-list">
            <li><span class="label">退住日期</span><span class="value">{{ form.checkoutDate || '-' }}</span></li>
            <li><span class="label">退住原因</span><span class="value">{{ formatReason(form.reason) || '-' }}</span></li>
            <li><span class="label">备注</span><span class="value">{{ form.remark || '-' }}</span></li>
            <li><span class="label">申请人</span><span class="value">{{ form.applyName || '-' }}</span></li>
            <li><span class="label">申请时间</span><span class="value">{{ form.applyTime || '-' }}</span></li>
          </ul>
        </el-card>

        <!-- 上传解除协议区域（移除文件必填校验） -->
        <el-card class="upload-card">
          <h3>上传解除协议</h3>
          <el-form :model="dissolutionForm" ref="dissolutionFormRef" label-width="120px" class="form-content">
            <el-form-item label="合同编号" prop="contractNo">
              <el-input v-model="dissolutionForm.contractNo" readonly />
            </el-form-item>
            <el-form-item 
              label="解除日期" 
              prop="dissolutionDate"
              :rules="[{ required: true, message: '请选择解除日期', trigger: 'change' }]"
            >
              <el-date-picker 
                v-model="dissolutionForm.dissolutionDate" 
                type="date" 
                placeholder="选择解除日期" 
                value-format="YYYY-MM-DD"
                :disabled-date="disabledPastDate"
              />
            </el-form-item>
            <el-form-item 
              label="解除协议" 
              prop="dissolutionFile"
            >
              <file-upload v-model="dissolutionForm.dissolutionFile" :limit="1" :fileType="['pdf']" />
            </el-form-item>
          </el-form>
        </el-card>
      </div>

      <div class="right-content">
        <!-- 操作记录区域 -->
        <el-card class="operation-record-card">
          <div class="record-header">
            <h3>操作记录</h3>
            <div class="record-status">
              <span class="status-badge completed">已完成</span>
            </div>
          </div>
          <div class="record-timeline" v-if="operationRecords.length">
            <div v-for="(record, index) in operationRecords" :key="index" class="timeline-item completed">
              <div class="timeline-dot">
                <el-icon :color="record.status === '已拒绝' ? '#f56c6c' : '#67c23a'" size="16">
                  <Check v-if="record.status === '已发起' || record.status === '已通过'" />
                  <Close v-else-if="record.status === '已拒绝'" />
                  <Clock v-else />
                </el-icon>
              </div>
              <div class="timeline-content">
                <div class="timeline-title">{{ record.action }}</div>
                <div class="timeline-desc">{{ record.operator }} ({{ record.status }})</div>
                <div class="timeline-time">{{ record.time || '-' }}</div>
                <div class="timeline-opinion" v-if="record.opinion && record.opinion !== '-'">
                  <div class="timeline-opinion-label">审批意见：</div>
                  <div class="timeline-opinion-text">{{ record.opinion }}</div>
                </div>
              </div>
            </div>
          </div>
          <div v-else class="loading-tip">加载中...</div>
        </el-card>
      </div>
    </div>

    <!-- 底部按钮 -->
    <div class="bottom-buttons">
      <el-button @click="handleBack" size="default">返回</el-button>
      <el-button type="primary" @click="handleSubmit" size="default">提交</el-button>
    </div>
  </div>





</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Check, Close, Clock } from '@element-plus/icons-vue';
import { getContent, addContent } from '@/api/drop/content';
import useUserStore from '@/store/modules/user';
import { getAccraditationrecordByDropContentId,updateAccraditationrecord } from '@/api/accraditationrecord/accraditationrecord';
import { getUser } from '@/api/system/user';
import FileUpload from '@/components/FileUpload';

const roleName = ref('');

// 接收父组件参数
const props = defineProps({
  stepNum: {
    type: Number,
    default: 3,
    required: true
  },
  dropContentId: {
    type: [String, Number],
    default: '',
    required: true
  }
});

// 向父组件传递事件
const emit = defineEmits(['submit-step', 'back-to-list']);

// 当前登录用户
const userStore = useUserStore();
const currentUser = ref(userStore.nickName || '管理员');

// 步骤一、二传递的基础数据
const form = ref({});

// 步骤三表单数据
const dissolutionForm = ref({
  contractNo: '',       // 合同编号（继承自基础数据）
  dissolutionDate: '',  // 解除日期
  dissolutionFile: ''   // 上传的协议文件路径（非必填）
});
const dissolutionFormRef = ref(null);

// 操作记录
const operationRecords = ref([]);

// 格式化退住原因
const formatReason = (reason) => {
  const reasonMap = {
    'personal': '个人原因',
    'recovery': '身体康复',
    'dissatisfaction': '服务不满意',
    'other': '其他原因'
  };
  return reasonMap[reason] || reason;
};

// 禁用日期范围：只能选择今天到退住日期之间
const disabledPastDate = (date) => {
  if (!date) return false;
  
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  
  // 如果退住日期不存在，则只限制到今天之前
  if (!form.value.checkoutDate) {
    return date < today;
  }
  
  // 解析退住日期
  const checkoutDate = new Date(form.value.checkoutDate);
  checkoutDate.setHours(0, 0, 0, 0);
  
  // 禁用今天之前和退住日期之后的日期
  return date < today || date > checkoutDate;
};


// 加载步骤二传递的数据
const fetchData = async () => {
  if (!props.dropContentId) {
    ElMessage.error('未获取到有效的数据ID，请返回上一步重新提交');
    return;
  }

  try {
    const res = await getContent(props.dropContentId);
    if (res.data?.currentInfo) {
      const currentInfo = JSON.parse(res.data.currentInfo);
      form.value = currentInfo;

      // 初始化表单（继承合同编号）
      dissolutionForm.value.contractNo = currentInfo.contract || '';

      // 回显历史数据（如驳回后重新进入）
      if (currentInfo.dissolutionDate) {
        dissolutionForm.value.dissolutionDate = currentInfo.dissolutionDate;
      }
      if (currentInfo.dissolutionFile) {
        dissolutionForm.value.dissolutionFile = currentInfo.dissolutionFile;
      }

      // 构建操作记录
      operationRecords.value = [
        {
          action: '发起申请-申请退住',
          operator: currentInfo.applyName || '-',
          status: '已发起',
          time: currentInfo.applyTime || '-',
          opinion: ''
        },
        {
          action: '(角色) 审批-申请审批',
          operator: currentInfo.approver || '-',
          status: currentInfo.approvalResult === 'approvalPass' ? '已通过' : '已拒绝',
          time: currentInfo.approveTime || '-',
          opinion: currentInfo.approvalOpinion || '-'
        }
      ];
    } else {
      ElMessage.warning('未获取到有效的申请信息');
    }
  } catch (error) {
    console.error('加载数据失败：', error);
    ElMessage.error('加载信息失败，请重试');
  }
};

// 表单验证（暴露给父组件）
const validateForm = async () => {
  if (!dissolutionFormRef.value) return false;
  try {
    await dissolutionFormRef.value.validate();
    return true;
  } catch (error) {
    ElMessage.warning('请完善解除协议信息');
    return false;
  }
};

// 暴露验证方法
defineExpose({
  validateForm
});

// 返回按钮
const handleBack = () => {
  emit('back-to-list');
};

// 提交处理
const handleSubmit = async () => {
  // 1. 验证表单（仅校验解除日期）
  const isValid = await validateForm();
  if (!isValid) return;

  try {
    // 2. 合并所有数据
    const submitInfo = {
      ...form.value,  // 步骤一、二数据
      ...dissolutionForm.value,  // 步骤三数据（包含可选的文件）
      dissolutionSubmitter: currentUser.value,  // 新增：明确提交人
      dissolutionOperator: currentUser.value,  // 操作人
      dissolutionTime: new Date().toISOString().slice(0, 19).replace('T', ' '),  // 操作时间
      currentStep: props.stepNum
    };

    // 3. 调用接口保存
    const response = await addContent({
      currentInfo: JSON.stringify(submitInfo)
    });

    // 4. 传递新ID给步骤四
    if (response.code === 200 && response.dropContentId) {
      emit('submit-step', {
        newDropContentId: response.dropContentId,
        currentStep: props.stepNum
      });
      ElMessage.success('解除协议信息提交成功，进入下一步');
    } else {
      ElMessage.error(`提交失败：${response.msg || '未返回有效ID'}`);
    }

    //更新审批表
    const approvalRecords = await getAccraditationrecordByDropContentId(props.dropContentId);
    const uodateRecord=ref({
      id: approvalRecords.data.id,
      dropContentId: response.dropContentId,
      approverName: currentUser.value,
      currentStep: "解除合同",
      nextStep: "调整账单",
      stepNo: "4",
    })
    updateAccraditationrecord(uodateRecord.value);

  } catch (error) {
    console.error('提交失败：', error);
    ElMessage.error('提交失败，请检查网络');
  }
};

// 组件挂载时加载数据
onMounted(() => {
  //获取当前用户信息
  getUser(userStore.id).then(res => {
    roleName.value = res.data.roles[0].roleName;
  });

  console.log('步骤三接收参数：', {
    stepNum: props.stepNum,
    dropContentId: props.dropContentId
  });
  fetchData();
});
</script>

<style scoped>
/* 保留原有样式，新增加载提示样式 */
.other .ca{
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 80px;
}

.other h3 {
  margin-top: 20px;
}

.other .operation-record-card {
  margin-top: 30px;
  width: 600px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  height: auto;
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.record-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.record-status {
  display: flex;
  align-items: center;
}

.status-badge {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.processing {
  background-color: #e6f7ff;
  color: #1890ff;
  border: 1px solid #91d5ff;
}

.record-timeline {
  position: relative;
}

.timeline-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20px;
  position: relative;
}

.timeline-item:not(:last-child)::after {
  content: '';
  position: absolute;
  left: 12px;
  top: 32px;
  width: 2px;
  height: calc(100% + 4px);
  background-color: #e4e7ed;
}

.timeline-item.completed:not(:last-child)::after {
  background-color: #67c23a;
}

.timeline-item.processing:not(:last-child)::after {
  background-color: #409eff;
}

.timeline-dot {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  flex-shrink: 0;
  position: relative;
  z-index: 1;
}

.timeline-item.completed .timeline-dot {
  background-color: #f0f9ff;
  border: 2px solid #67c23a;
}

.timeline-item.processing .timeline-dot {
  background-color: #f0f9ff;
  border: 2px solid #409eff;
}

.timeline-content {
  flex: 1;
  padding-top: 2px;
}

.timeline-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.timeline-desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 6px;
}

.timeline-time {
  font-size: 12px;
  color: #999;
  margin-bottom: 8px;
}

.timeline-opinion {
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  padding: 12px;
  margin-top: 8px;
}

.opinion-label {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
  font-weight: 500;
}

.opinion-content {
  font-size: 14px;
  color: #333;
  line-height: 1.5;
}

.other img {
  width: 60px;
  height: 60px;
}

.oth {
  color: #333;
  font-size: 14px;
}


.third-page {
  padding: 20px;
}

.content-wrapper {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.left-content {
  flex: 2;
}

.right-content {
  flex: 1;
}

.basic-info-card, .apply-info-card, .upload-card, .operation-record-card {
  margin-bottom: 20px;
}

.info-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.info-list li {
  margin-bottom: 12px;
  display: flex;
  align-items: center;
}

.label {
  width: 120px;
  text-align: right;
  margin-right: 16px;
  color: #666;
  font-size: 14px;
}

.value {
  flex: 1;
  font-size: 14px;
  color: #333;
}

.view-link {
  color: #409eff;
  cursor: pointer;
  margin-left: 8px;
}

.record-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.record-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 15px;
  font-size: 14px;
  flex-wrap: wrap;
}

.record-icon {
  margin-right: 10px;
  margin-top: 2px;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #409eff;
  margin-top: 6px;
}

.record-content {
  flex: 1;
  color: #333;
}

.record-content p {
  margin: 4px 0;
}

.record-time {
  width: 150px;
  text-align: right;
  color: #999;
  margin-left: 10px;
}

.approval-opinion {
  background-color: #f5f7fa;
  padding: 8px;
  border-radius: 4px;
  margin-top: 5px;
  width: 100%;
}

.bottom-buttons {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 20px;
}

.loading-tip {
  text-align: center;
  padding: 20px;
  color: #999;
  font-size: 14px;
}

/* Timeline styles for v-else */
.third-page .record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.third-page .record-status {
  display: flex;
  align-items: center;
}

.third-page .status-badge.completed {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
  background-color: #f0f9ff;
  color: #67c23a;
  border: 1px solid #95d475;
}

.third-page .record-timeline {
  position: relative;
}

.third-page .timeline-item.completed:not(:last-child)::after {
  background-color: #67c23a;
}

.third-page .timeline-opinion-label {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
  font-weight: 500;
}

.third-page .timeline-opinion-text {
  font-size: 14px;
  color: #333;
  line-height: 1.5;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}
</style>